package com.xzh.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class Hellocontroller {
    @Value("${sso.server.url}")
    String ssoserverUrl;
    //无需登录就能访问
    @GetMapping("/hello")
    public String hello()
    {
        return "hello";
    }


    @GetMapping("/employee")
    public String employee(Model model, HttpSession session,@RequestParam(value = "token",required = false) String token)
    {
        if(!StringUtils.isEmpty(token))
        {
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> entity = restTemplate.getForEntity("http://sso.com:8080/userinfo?token=" + token, String.class);
            String body = entity.getBody();
            System.out.println(body+"=====");
            session.setAttribute("loginUser",body);
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser==null)
        {
            //没登录
            //跳转过去之后，使用url上的请求参数表示自己是哪个页面
            //redirect_url=http://client1.com:8081/employee
            return "redirect:"+ssoserverUrl+"?redirect_url=http://client1.com:8081/employee";
        }
        else {
            //登录，直接跳转首页
            List<String> emps = new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            model.addAttribute("emps", emps);
            return "list";
        }
    }

}
